/*	
 * 图片旋转根据自定义角度自由旋转，缩放。
 * 
 * eg：
 *   html代码：<div id="img"><img src="img/4.jpg" /></div>
 * 	 js代码：
 * 		1、设置模式，默认自动选择
 * 			RSImageFormat(["css3"]);
 * 		2、调用插件方法
 * 			window.RSI = new RSImage({
						id:"img",
						target:$("#img"),
					//	src:"img/2.jpg",
						isRotate:false,
						deg:0,
						isScale:true,
						isPartZoom:false,
						scale:1
					});
 * 提供以下方法
 * 		设置全局默认参数			RSImageFormat(config);config为需要设置的参数
 * 		旋转							RSI.rotate([angle]):angle为旋转的角度
 * 		放大							RSI.zoomIn([scale]):scale缩放的大小
 * 		缩小							RSI.zoomOut([scale]):scale缩放的大小
 * 		水平翻转						RSI.horizontal();水平翻转
 * 		垂直翻转						RSI.vertical();垂直翻转
 * 		鼠标拖动旋转				RSI.drag();鼠标拖动旋转，受isRotate参数影响，isRotate=true时支持旋转，false不支持
 * 		鼠标滚动缩放				RSI.scroll();鼠标滚动旋转，受isScale参数影响，isScale=true时支持缩放，false不支持
 * 		局部放大						RSI.partZoomOut()
 *	Ahthor：MaxJh
 * 	Copyright：MaxJh
 * 	Version：v0.0
 * */
;(function(win,$){
	var RSImage = function(config){
		var self = this;
		this._setConfig(config);
		//支持的mode模式，canvas，css3，filter
		this._supportJson = this._support();
		if($.isEmptyObject(this._supportJson)){
			if($.isFunction(MaxAlert)){
				MaxAlert("你的浏览器不支持canvas,css3,filter,小的能力有限没法兼容到！");
			}else{
				alert("你的浏览器不支持canvas,css3,filter,小的能力有限没法兼容到！");
			}
		}
		//设置当前处理图片的模式和处理图片的参数
		this._setMode_modeParm();
		this._initMode();
		this._onPreLoad(function(w,h){
			self._initContainer();
			self._naturalWidth = w;
			self._naturalHeight = h;
			self.mode && self.init();
			
			self._initScale = self.config.scale;
			self._initDeg = self.config.deg;
			self.config.y = self.config.x = self.config.scale
			self.mode && self.load();
			//console.log("3---self.show()")
			self.mode && self.show();
			self.mode && self.dispose();
			
			self._creatOpFun();
			
			if(self.config.isRotate){
				self.drag();
			}
			if(self.config.isScale){
				self.scroll();
			}
			if(self.config.isPartZoom){
				self.partZoomOut();
			}
			return self;
		})
	};
	
	RSImage.MODE = ["canvas","css3","filter"];
	//默认参数
	RSImage.DEFAULTS = {
		id:null,									//容器ID
		target:null,							//容器对象
		src:null,									//图片路径
		isRotate:false,						//是否支持旋转
		deg:0,										//默认角度
		angle:1,									//角度调整步长
		isScale:true,							//是否支持鼠标滚动缩放
		scale:1, 									//默认缩放比例
		zoom:0.01,								//缩放步长
		isPartZoom:false					//是否启用鼠标移动局部放大
	};
	
	RSImage.prototype = {
		_onPreLoad:function(cb){
			var self = this,
					imgDom = this._img;
			if(!!window.ActiveXObject){//IE
	   		imgDom.onreadystatechange = function(){
	   			if(this.readyState == "complete"){
	   				self._naturalWidth = imgDom.width;
	   				self._naturalHeight = imgDom.height;
	   				cb&&cb(self._naturalWidth,self._naturalHeight);
	   			}
	   		}
	   	}else{
	   		imgDom.onload = function(){
	   			self._naturalWidth = imgDom.width;
   				self._naturalHeight = imgDom.height;
   				cb&&cb(self._naturalWidth,self._naturalHeight);
	   		};
	   		imgDom.src = self.config.src;
	   	};
	   	imgDom.onerror = function(){
			if($.isFunction(MaxAlert)){
				MaxAlert("哎呀，图片加载出问题了...")
			}else{
				alert("哎呀，图片加载出问题了...")
			}
	   		}
	   	imgDom.src = self.config.src;
		},
		//获取图片信息
		_getImgInfo:function(){
			
		},
		//将当前采用处理图片模式的方法载入插件
		_initMode:function(){
			var self = this;
			self.mode && $.each(RSImage[self.mode], function(key,value) {
				if($.isFunction(value)){
					self[key] = function(){
						/*value.apply(self,[].slice.call(arguments));*/
						value.call(self,arguments);
						//self.show();
					}
				}
			});
		},
		//设置当前处理图片的模式和处理图片的参数
		_setMode_modeParm:function(){
			this.mode = this._supportJson.name;
			this.modeParm = this._supportJson.value;
		},
		_setConfig:function(config){
			this.config = {};
			$.extend(true, this.config,RSImage.DEFAULTS, config);
			// 容器对象
			this._container = $(this.config.target) || $("#"+this.config.id);
			if(!this.config.src){
				//图片路径
				this.config.src = this._container.children("img").eq(0).attr("src") || this._container.data("src"); 
			}
			//图片对象
			this._img = new Image();
			//容器大小
			this._clientWidth = this._container.width();
			this._clientHeight = this._container.height();
			//备份样式
			this._style = "";
			this._class = "";
			this._id = "";
		},
		_initContainer:function(){
			var self = this,
					imgStyle = this._style,
					container = this._container;
			//给容器添加定位参数		
			if(!container.css("position") || container.css("position") != "static"){
				container.css({
					"position":"relative"
				});
			};
			//保存容器内图片样式
			this.curImg = container.children("img").eq(0)||container.children().eq(0);
			this._style = this.curImg.attr("style");
			this._class = this.curImg.attr("class");
			this._id = this.curImg.attr("id");
			container.css({
				"overflow":"hidden"
			})
			//改变容器内图片样式
			/*this.curImg.css({
				visibility:"hidden"
			});*/
		//	//console.log(imgStyle);
		},
		_support:function(){
			var self = this;
			var supportJson = {}
			var mode = RSImage.MODE;
			$.each(mode, function(i,n) {
				var value = RSImage[n].support;
				if(value == true || ( $.isArray(value) && value.length>0)){
					supportJson.name = mode[i]; 
					supportJson.value = value;
					return false;
				}
			});
			return supportJson;
		},
		
		_creatOpFun:function(){
			var self = this;
			$.each(RSImage.methods, function(key,value) {
				self[key] = function(){
					value.apply(self,[].slice.call(arguments));
					//console.log("1--self.show()");
					self.mode && self.show();
				}
			});
		},
		_getMatrix:function (radian, x, y) {
			var Cos = Math.cos(radian), Sin = Math.sin(radian);
			return {
				M11: Cos * x,
				M12:-Sin * y,
				M21: Sin * x,
				M22: Cos * y
			};
		},
		init:function(){},
		load:function(){},
		show:function(){},
		dispose:function(){},
		zoomIn:function(){},
		zoomOut:function(){},
		rotate:function(){},
		rotateLeft:function(){},
		rotateRight:function(){},
		vertical:function(){},
		horizontal:function(){},
		reset:function(){},
		drag:function(){},
		scroll:function(){},
		partZoomOut:function(){}
	};
	
	RSImage.canvas = {
		//TODO canvas模式的处理图片方式
		support:function(){
			return "getContext" in document.createElement('canvas');
		}(),
		init:function(){
			//TODO 初始化canvas
			//console.log("canvas init");
			var self = this;
			this.canvas = $("<canvas></canvas>");
			this.canvas.attr({
				"width":self._clientWidth,
				"height":self._clientHeight
			});
			this._container.append(this.canvas);
			//js对象获取context
			this._context = (this.canvas).get(0).getContext('2d');
			self.config.scale = Math.min((self._clientWidth / self._naturalWidth),(self._clientHeight / self._naturalHeight),1);
		},
		load:function(){
			//console.log("canvas load");
		},
		show:function(){
			//console.log("canvas show");
			var img = this._img,
					context = this._context,
					clientWidth = this._clientWidth,
					clientHeight = this._clientHeight;
				//canvas变换
				context.save();
				context.clearRect( 0, 0, clientWidth, clientHeight );//清空内容
				context.translate( clientWidth / 2 , clientHeight / 2 );//中心坐标
				context.rotate( this.config.deg * Math.PI/180 );//旋转
				context.scale( this.config.y, this.config.x );//缩放
				context.drawImage( img, -img.width / 2, -img.height / 2 );//居中画图
				context.restore();
		},
		dispose:function(){
			//console.log("canvas dispose");
			this._container.children("img").eq(0).remove();
		}
	};
	
	RSImage.css3 = {
		//TODO css3模式的处理图片方式
		support:function(){
				var arr = [];
				var style = document.createElement("div").style;
				$.each(
						[ "transform", "MozTransform", "webkitTransform", "OTransform" ],
						function(i,css){
							if ( css in style ) {
								arr.push(css);
							}
						});
				return arr;
			}(),
		init:function(){
			//TODO 初始化css3处理的图片
			var self = this;
			self.config.Css3Scale = Math.min((self._clientWidth / self._naturalWidth),(self._clientHeight / self._naturalHeight));
		},
		load:function(){
			//console.log("css3 load()");
		},
		show:function(){
			//console.log("css3 show()");
			var self = this;
			var matrix = self._getMatrix(self.config.deg / 180 * Math.PI,self.config.y,self.config.x);
			var MatrixStyle = "matrix("
					+ matrix.M11.toFixed(16) + "," + matrix.M21.toFixed(16) + ","
					+ matrix.M12.toFixed(16) + "," + matrix.M22.toFixed(16) + ", 0, 0)";
			
			self.curImg.css({
				"transform":MatrixStyle
			});
		},
		partZoomOut:function(){
			
		},
		dispose:function(){
			//console.log("css3 dispose()");
		}
	};
	
	RSImage.filter = {
		//TODO filter模式的处理图片方式
		support: function(){ return "filters" in document.createElement("div"); }(),
		init:function(){
			//console.log("filter init()");
			var self = this;
			self.config.filterScale = Math.min((self._clientWidth / self._naturalWidth),(self._clientHeight / self._naturalHeight));
		},
		load:function(){
			//console.log("filter load()");
		//	this._img.onload = null;//防止ie重复加载gif的bug
		},
		show:function(){
			//console.log("filter show()");
			var self = this;
			var matrix = self._getMatrix(self.config.deg / 180 * Math.PI,self.config.y,self.config.x);
			var MatrixStyle = "matrix("
					+ matrix.M11.toFixed(16) + "," + matrix.M21.toFixed(16) + ","
					+ matrix.M12.toFixed(16) + "," + matrix.M22.toFixed(16) + ", 0, 0)";
			//filter:progid:DXImageTransform.Microsoft.Matrix(M11=-1.414,M12=-1.414,M21=0.1.414,M22=-1.414,SizingMethod='auto expand');
			self.curImg.css({
				"filter":"progid:DXImageTransform.Microsoft.Matrix(M11="+matrix.M11+",M12="+matrix.M12+",M21="+matrix.M21+",M22="+matrix.M22+",SizingMethod='auto expand');"
			});
			self.curImg.css({
				"left":(self._clientWidth - self.curImg.width()) / 2,
				"top":(self._clientHeight - self.curImg.height()) / 2
			})
		},
		dispose:function(){
			//console.log("filter dispose()");
		}
	};
	//操作函数
	RSImage.methods = {
		zoomIn:function(scale){
			//TODO	放大
			$("#console").html("放大");
			//console.log("放大");
			if(scale){
				this.config.y = this.config.x = scale;
			}else{
				
				this.config.y>0?this.config.y+=this.config.zoom:this.config.y-=this.config.zoom
				this.config.x>0?this.config.x+=this.config.zoom:this.config.x-=this.config.zoom
			/*	this.config.y += this.config.zoom;
				this.config.x += this.config.zoom;*/
			};
		},
		
		zoomOut:function(scale){
			//TODO 缩小
			$("#console").html("缩小");
			//console.log("缩小");
			if(scale){
				this.config.y = this.config.x = scale;
			}else{
				this.config.y>0?this.config.y-=this.config.zoom:this.config.y+=this.config.zoom
				this.config.x>0?this.config.x-=this.config.zoom:this.config.x+=this.config.zoom
			};
		//	this.config.y = this.config.y>0?this.config.y:0;
		//	this.config.x = this.config.x>0?this.config.x:0;
		},
		
		partZoomOut:function(){
			var self = this;
			//1、判断图片宽或高大小是否大于容器的款或高，大于则继续执行，否则不执行
			//2、鼠标移到容器上触发后续操作
			//3、隐藏容器下的canvas或img，visibility：hidden
			//4、给容器添加css属性，backgroud-image:url(this.config.src);
			//5、根据鼠标在容器所在的位置，显示图片对应的位置；background-position：-x -y；
			if(self._naturalWidth > self._clientWidth || self._naturalHeight > self._clientHeight){
				if(self._container.css("position") == "static"){
					self._container.css("position","relative");
				}
				
				self.divContainer = $("<div class='divContainer'></div>");
				self.divImg = $("<img />");
				self.divContainer.css({
					"position":"absolute",
					"width":"100%",
					"height":"100%",
					"top":0,
					"left":0,
					"overflow":"hidden"
				});
				self.divImg.css({
					"cursor":"move",
					"border":0,
					"display":"block"
				});
				if(!self._container.find(".divContainer").length){
					self._container.append(self.divContainer);
				}
				if(!self.divContainer.find("img").length){
					self.divContainer.append(self.divImg);
				}
				
				
				self._container.on("mousemove",function(e){
					self.config.target.children().not(".divContainer").css("visibility","hidden");
					self.divImg.css("visibility","visible");
					//图片的宽度和高度
					var imgw = self._naturalWidth;
					var imgh = self._naturalHeight;
					//盒子宽度和高度
					var boxw = self._clientWidth;
					var boxh = self._clientHeight;
					if(self.config.deg % 180 == 1){
						boxw = self._clientHeight;
						boxh = self._clientWidth;
					}
					//盒子和图片宽度百分比
					var wp = imgw / boxw ;
					//盒子和图片高度百分比
					var hp = imgh / boxh ;
					//盒子的相对于文档区域x轴和y轴距离
					var l = self._container.offset().left;
					var t = self._container.offset().top;
					//相对于浏览器可视区域的x轴坐标
					var x = e.clientX || e.pageX ;
					//相对于浏览器的可视区域y轴坐标
					var y = e.clientY || e.pageY ;
					//相对于文档区域的最上部距离
					var st = $(document).scrollTop();
					var xx = (x-l) * wp ;
					var yy = (y+st-t) * hp ;
					if(xx>(imgw-boxw)){
						xx = imgw-boxw
					}
					//判断yy的边界
					if(yy>(imgh-boxh)){
						yy = imgh-boxh;
					}
					var bgposition = "";
					if(self.config.deg % 180 == 1){
						bgposition = -yy+"px "+(-xx)+"px";
					}else{
						bgposition = -xx+"px "+(-yy)+"px";
					}
					self.divImg.attr("src",self.config.src);
					self.divImg.css({
							"width":self._naturalWidth,
							"height":self._naturalHeight,
							"margin-left":-xx,
							"margin-top":-yy,
							"transform":"rotate("+self.config.deg+"deg)"
						});
				}).on("mouseleave",function(){
					self.config.target.children().css("visibility","visible");
					self.divImg.css("visibility","hidden");
				})
			}
		},
		
		rotateParm:function(scale){
			if(scale){
				this.config.y = this.config.x = scale;
			}else{
				if(this.mode == "css3"){
					if(Math.abs(this.config.deg)%180 == 90){
						this.config.scale = Math.min((this._clientWidth / this._naturalHeight/this.config.Css3Scale),(this._clientHeight / this._naturalWidth/this.config.Css3Scale),1);
					}else{
						this.config.scale = 1;
					}
					this.config.y = this.config.x = this.config.scale;
				}else if(this.mode == "canvas"){
					if(Math.abs(this.config.deg)%180 == 90){
						this.config.scale = Math.min((this._clientWidth / this._naturalHeight),(this._clientHeight / this._naturalWidth),1);
					}else{
						this.config.scale = this._initScale;
					}
					this.config.y = this.config.x = this.config.scale;
				}else if(this.mode == "filter"){
					if(Math.abs(this.config.deg)%180 == 90){
						this.config.scale = Math.min((this._clientWidth / this._naturalHeight/this.config.filterScale),(this._clientHeight / this._naturalWidth/this.config.filterScale),1);
					}else{
						this.config.scale = 1;
					}
					this.config.y = this.config.x = this.config.scale;
				}
			}
		},
		rotateLeft:function(scale){
			//TODO 左旋转、逆时针旋转
			$("#console").html("左旋转、逆时针旋转");
			//console.log("左旋转、逆时针旋转");
			
			this.config.deg -= 90 ;
			this.rotateParm(scale);
		},
		rotateRight:function(scale){
			//TODO 右旋转、顺时针旋转 90度
			$("#console").html("右旋转、顺时针旋转 90度");
			//console.log("右旋转、顺时针旋转");
			this.config.deg += 90 ;
			this.rotateParm(scale);
		},
		
		rotate:function(angle){
			//TODO 根据角度旋转
			$("#console").html("根据角度旋转");
			if(angle){
				this.config.deg += angle
			}else{
				this.config.deg += this.config.angle ;
			}
		},
		
		vertical:function(){
			//TODO 垂直翻转
			$("#console").html("垂直翻转");
			//console.log("垂直翻转");
			this.config.deg = 180 - this.config.deg;
			if(this.mode == "filter"){
				
				if(Math.abs(this.config.deg)%180 == 90){
					this.config.y *= -1;
				}else{
					this.config.y *= -1;
				}
			}else{
				this.config.y *= -1;
			}
			
		},
		
		horizontal:function(){
			//TODO 水平翻转
			$("#console").html("水平翻转");
			//console.log("水平翻转");
			this.config.deg = 180 - this.config.deg;
			if(this.mode == "filter"){
				
				if(Math.abs(this.config.deg)%180 == 90){
			//		this.config.x *= -1;
					this.config.x *= -1;
				}else{
					this.config.x *= -1;
				}
			}else{
				this.config.x *= -1;
			}
		},
		
		reset:function(){
			//TODO 重置
			$("#console").html("重置");
			//console.log("重置");
			this.config.y = this.config.x = this._initScale;
			this.config.deg = this._initDeg;
		},
		
		drag:function(){
			//TODO 鼠标拖动旋转
			var self = this;
			var container_left = self._container.offset().left;
			var container_top = self._container.offset().top;
			var center_left = container_left + self._clientWidth / 2;
			var center_top = container_top + self._clientHeight / 2;
			
			self._container.on("mousedown",function(event){
				var ev = event || window.event;
				ev.stopPropagation();
				ev.preventDefault();
				var x = ev.pageX,
						y = ev.pageY;
				var radian = Math.atan2( y - center_top, x - center_left );
				self._container.on("mousemove",function(event){
					var evv = event || window.event;
					evv.stopPropagation();
					evv.preventDefault();
						var xx = evv.pageX,
							yy = evv.pageY,
							deg = Math.atan2((yy-center_top),(xx-center_left)) - radian;
						//	console.log(deg)
							/**
							角度转弧度  弧度 = 角度 * Math.PI/180 
							弧度转角度  角度 = 弧度  / Math * 180
							 */
							deg = deg * 180 / Math.PI / 10;
							if(deg)self.rotate(deg);
				}).on("mouseup",function(){
					self._container.off("mousemove",null);
					self._container.off("mouseup",null);
				})
			});
		},
		
		scroll:function(){
			//TODO 鼠标滚动缩放  ,DOMMouseScroll为火狐支持的鼠标滚轮事件，其他为mousewheel
			/**
			 * 火狐浏览器 
			 * 向上 滚轮步长为-3
			 * 向上 滚轮步长为 3
			 * 
			 * 其他浏览器
			 * 向上 滚轮步长为    120
			 * 向上 滚轮步长为 -120
			 */
			var self = this;
			self._container.on("mousewheel DOMMouseScroll",function(event){
				var ev = event || window.event;
				ev.stopPropagation();
				ev.preventDefault();
				var wheelStep = (ev.originalEvent.wheelDelta / 12000) || (ev.originalEvent.detail / -300);
				self.config.y>0?self.config.y+=wheelStep:self.config.y-=wheelStep;
				self.config.x>0?self.config.x+=wheelStep:self.config.x-=wheelStep;
				self.mode && self.show();
			});
		}
	}
	win.RSImage = RSImage;
	win.RSImageFormat = function(config){
		RSImage.MODE = config;
	}
})(window,jQuery);
